use sea_orm::{Set};
use serde::{Deserialize, Serialize};

use crate::entity::account_info;
use crate::entity::account_info::Model as AccountInfo;
use crate::utils::db_util::{ConditionExpr, ConditionGroupOp, ConditionOp, get_global_db_util, opt_str_to_value};
use crate::utils::ajax_result::AjaxResult;
use crate::utils::page_result::PageResult;

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ShelfListReq{
    pub page_num:Option<u64>,
    pub page_size:Option<u64>,
    pub syn_zh:Option<String>,

    pub htype:Option<String>,
    pub hstatus:Option<String>,
    pub wgname:Option<String>,
    pub zh:Option<String>,
    pub hid:Option<String>,

    pub zhw_hid:Option<String>,
    pub uhz_hid:Option<String>,
    pub zz_hid:Option<String>,

    pub zhw_zt:Option<String>,
    pub uhz_zt:Option<String>,
    pub zz_zt:Option<String>,
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ShelfMonitorReq{
    pub zh:Option<String>,
    pub off_on: Option<i32>,
    pub remark: Option<String>,
    pub usort: Option<i32>,
}

pub async fn modify_shelf_monitor(data: ShelfMonitorReq) -> AjaxResult<()> {
    let dbutil = get_global_db_util();
    // 创建一个可变的 ActiveModel
    let mut active_model = account_info::ActiveModel {
        ..Default::default()
    };
    // 有条件地设置 remark 和 usort 字段
    if let Some(remark) = data.remark {
        active_model.remark = Set(Some(remark));
    }

    if let Some(usort) = data.usort {
        active_model.usort = Set(Some(usort));
    }

    if let Some(off_on) =data.off_on {
        active_model.off_on = Set(Some(off_on));
    }

    let result=dbutil.query::<account_info::Entity>()
        .eq_str(account_info::Column::Zh,data.zh)
        .update(dbutil.get_connection(),active_model).await;

    match result {
        Ok(_) => {
            AjaxResult::succeed_without_data()
        }
        Err(_) => {
            AjaxResult::internal_error("修改失败")
        }
    }
}

pub async fn get_shelf_list(mut req: ShelfListReq) -> PageResult<AccountInfo> {
    let dbutil = get_global_db_util();
    let mut query=dbutil.query::<account_info::Entity>();
    let page_num = req.page_num.unwrap_or(1);
    let page_size = req.page_size.unwrap_or(10);

    if let Some(htype) = &req.htype {
        if !htype.is_empty() {
            match htype.as_str() {
                "1" => {
                    query = query.is_not_null(account_info::Column::ZhwHid);
                    req.zhw_zt = req.hstatus.clone();
                }
                "2" => {
                    query = query.is_not_null(account_info::Column::UhzHid);
                    req.uhz_zt = req.hstatus.clone();
                }
                "3" => {
                    query = query.is_not_null(account_info::Column::ZzHid);
                    req.zz_zt = req.hstatus.clone();
                }
                "0" => {
                    if let Some(hstatus) = &req.hstatus {
                        if !hstatus.is_empty() {
                            // 构建查询条件
                            let status_condition = if hstatus == "1" {
                                // 出租中: zhw_zt = 1 或者 zz_zt = 2
                                ConditionExpr::Group(
                                    ConditionGroupOp::Or,
                                    vec![
                                        ConditionExpr::Simple(account_info::Column::ZhwZt, ConditionOp::Eq, opt_str_to_value(Some("1".to_string()))),
                                        ConditionExpr::Simple(account_info::Column::ZzZt, ConditionOp::Eq, opt_str_to_value(Some("2".to_string()))),
                                    ]
                                )
                            } else if hstatus == "2" {
                                // 上架中：zhw_zt = '0' OR zz_zt = '1'
                                ConditionExpr::Group(
                                    ConditionGroupOp::Or,
                                    vec![
                                        ConditionExpr::Simple(account_info::Column::ZhwZt, ConditionOp::Eq, opt_str_to_value(Some("0".to_string()))),
                                        ConditionExpr::Simple(account_info::Column::ZzZt, ConditionOp::Eq, opt_str_to_value(Some("1".to_string()))),
                                    ]
                                )
                            }else {
                                // 未出租: (zhw_zt != 1 或者 zhw_zt 为空) 并且 (zz_zt != 2 或者 zz_zt 为空)
                                let zhw_condition = ConditionExpr::Group(
                                    ConditionGroupOp::Or,
                                    vec![
                                        ConditionExpr::Simple(account_info::Column::ZhwZt, ConditionOp::Ne, opt_str_to_value(Some("1".to_string()))),
                                        ConditionExpr::Simple(account_info::Column::ZhwZt, ConditionOp::IsNull, opt_str_to_value(Some("1".to_string()))),
                                    ]
                                );

                                let zz_condition = ConditionExpr::Group(
                                    ConditionGroupOp::Or,
                                    vec![
                                        ConditionExpr::Simple(account_info::Column::ZzZt, ConditionOp::Ne, opt_str_to_value(Some("2".to_string()))),
                                        ConditionExpr::Simple(account_info::Column::ZzZt, ConditionOp::IsNull, opt_str_to_value(Some("2".to_string()))),
                                    ]
                                );

                                ConditionExpr::Group(
                                    ConditionGroupOp::And,
                                    vec![zhw_condition, zz_condition]
                                )
                            };

                            // 添加构建好的条件到查询
                            query = query.add_group(ConditionGroupOp::And, vec![status_condition]);
                        }
                    }
                }
                _ => {} // 处理其他情况
            }
        }
    }

    if req.hid.is_some() && !req.hid.as_ref().unwrap().is_empty(){
        let hid_condition=ConditionExpr::Group(
            ConditionGroupOp::Or,
            vec![
                ConditionExpr::Simple(account_info::Column::ZhwHid,ConditionOp::Eq,opt_str_to_value(req.hid.clone())),
                ConditionExpr::Simple(account_info::Column::UhzHid,ConditionOp::Eq,opt_str_to_value(req.hid.clone())),
                ConditionExpr::Simple(account_info::Column::ZzHid,ConditionOp::Eq,opt_str_to_value(req.hid)),
            ]
        );
        query=query.add_group(ConditionGroupOp::And, vec![hid_condition])
    }

    // 执行查询（无需转换，直接使用 Model）
    let paginated_data = match query
        .eq_str(account_info::Column::ZhwZt,req.zhw_zt)
        .eq_str(account_info::Column::UhzZt,req.uhz_zt)
        .eq_str(account_info::Column::ZzZt,req.zz_zt)
        .like(account_info::Column::Zh,req.zh)
        .like(account_info::Column::Wgname,req.wgname)
        .order_by(account_info::Column::Usort, sea_orm::Order::Desc)
        .order_by(account_info::Column::Id, sea_orm::Order::Asc)
        .paginate(dbutil.get_connection(), page_num, page_size)
        .await
    {
        Ok(data) => data,
        Err(e) => {
            log::error!("数据库查询失败: {:?}", e);
            return PageResult::empty();
        }
    };

    PageResult::succeed(paginated_data.items, paginated_data.total)
}